package com.example.demo.admin.gecco.crawler.mzt.image;

import com.example.demo.core.util.HttpClientUtil;
import org.apache.commons.collections.map.HashedMap;
import java.io.File;

import java.util.Map;

public class DownloadImage implements Runnable {


    private String imageSrc;
    private String imageName;

    private String mSavePath;

    private String parentDir;

    public DownloadImage(String imageSrc, String savePath) {
        this.imageSrc = imageSrc;
        mSavePath = savePath;

    }

    private boolean isImageExists() {
        File dir = new File(mSavePath);
        if(!dir.exists()) {
            dir.mkdirs();
        }

        String[] splits = imageSrc.split("/");
        imageName = splits[splits.length - 1];

        parentDir = splits[splits.length - 2];

        File parDir = new File(mSavePath+File.separator+parentDir);
        if(!parDir.exists()) {
            parDir.mkdirs();
        }

        return new File(dir + File.separator + imageName).exists();
    }

    @Override
    public void run() {
        if(isImageExists()) {
            Spider.failedCount++;
            return ;
        }

        Spider.failedCount = 0;


        System.out.println("开始下载妹子：" + imageName);


        try {

            String saveFile = mSavePath + File.separator+parentDir+File.separator + imageName;

            Map<String,String> heads = new HashedMap();
            heads.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
            heads.put("Referer","104.20.218.20:443");
            HttpClientUtil.me().downLoadFile(saveFile,imageName,heads);


            System.out.println("妹子" + imageName + "下载完成");

        }catch(Exception e) {
            e.printStackTrace();
            System.err.println("抛出异常并不可怕， 这个妹子我不要了！\n删除妹子" + imageName);
            new File(mSavePath + File.separator+parentDir+File.separator + imageName).delete();
            return;
        }
    }
}